package com.c.ctgproject.ui.service

import android.content.Intent
import android.os.Handler
import android.view.View
import android.widget.AdapterView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.c.ctgproject.R
import com.c.ctgproject.adapter.service.ServiceEditCheckAdapter
import com.c.ctgproject.adapter.service.ServiceTrackingSpannerAdapter
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.entity.service.*
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.dialog.ServicePayTypeDialog
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_service_order_edit.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.startActivity
import java.util.HashMap

/**
 *作者:LiBW
 *创建日期: 2021/7/1
 *描述:客服订单详情修改 页面 处理订单 页面
 */
class ServiceOrderEditActivity : BaseActivity(), ServiceEditCheckAdapter.ServiceEditCallback, ServicePayTypeDialog.ServicePayTypeDialog {
    private val mViewModel by lazy { ViewModelProvider(this)[ServiceOrderDetailViewModel::class.java] }
    private val mAdapter by lazy { ServiceEditCheckAdapter(this, mList, this) }

    //订单属性 2:预订单 3:意向订单
    private val dataType by lazy { intent.getIntExtra(MyConstants.DATA_TYPE, -1) }
    override fun getLayout() = R.layout.activity_service_order_edit
    private val mList = ArrayList<ServiceEditCheckBean>()
    private val mData by lazy { intent.getSerializableExtra(MyConstants.DATA) as ServiceCommonOrderEntity.DataBean.ListBean }
    private var mPayTypeEntity: PayTypeEntity? = null
    private var payTypeDialog: ServicePayTypeDialog? = null

    //物流
    private var trackingList = ArrayList<TrackingEntity.DataBean.ListBean>()
    private val trackingAdapter by lazy { ServiceTrackingSpannerAdapter(this, trackingList) }
    private var trackingSelectPosition = 0
    override fun event() {
        mViewModel.getOrderDetail(mData.suborderId.handlerNull(), mData.enterMode)
        //获取收款方式
        mViewModel.payType(mData.suborderId.handlerNull())
        mViewModel.error.observe(this, {
            loading.dismiss()
            MyLog.d("错误:$it")
            showToast(it)
        })
        //查询物流公司
        mViewModel.serviceTrackingList()
        val bean = TrackingEntity.DataBean.ListBean()
        bean.id = -1
        bean.orgname = "请选择物流公司"
        trackingList.add(bean)
        mTrackingSP.adapter = trackingAdapter
        mTrackingSP.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                trackingSelectPosition = position
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }

        when (dataType) {
            2 -> {
                //预订单
                mTopBTN.text = "订单待沟通"
            }
            3 -> {
                //意向订单
                mTopBTN.text = "回访记录"
            }
            else -> {
                mTopBTN.text = ""
            }
        }
        mViewModel.trackingResult.observe(this, {
            MyLog.d("物流回调:$it")
            val data = getGson().fromJson(it, TrackingEntity::class.java).data
            data?.list?.let { list ->
                trackingList.addAll(list)
                trackingAdapter.notifyDataSetChanged()

            }
        })
        mOrderNumTV.text = mData.orderCode.handlerNull()
        "创建时间: ${mData.createTime.handlerNull()}".also { mCreateTimeTV.text = it }
        val statue = when (mData.status) {
            "0" -> "状态: 已取消"
            "1" -> "状态: 待处理"
            "2" -> "状态: 待物流处理"
            "3" -> "状态: 已完成"
            "4" -> "状态: 待沟通"
            "5" -> "状态: 回退订单"
            "6" -> "状态: 待自送"
            else -> ""
        }

        mStatueTV.text = statue
        "车牌号: ${mData.ownerPlate}".also { mCarPlateTV.text = it }
        val isOperatingCar = "是否营运车辆: ${if (mData.isOperatingCar == "1") "是" else "否"}"
        mCommerialCar.text = isOperatingCar
        "车主: ${mData.carOwner}".also { mCarOwnerTV.text = it }
        "车主电话: ${mData.ownerPhone}".also { mOwnerPhoneTV.text = it }
        mSalesmanTV.text = mData.salesman.handlerNull()
        mCarAddressET.textSet(mData.carAddress.handlerNull())
        mCarBrandET.textSet(mData.carBrand.handlerNull())
        mReceiverET.textSet(mData.recipient.handlerNull())
        mReceiverPhoneET.textSet(mData.recipientPhone.handlerNull())
        mSendAddressET.textSet(mData.mailingAddress.handlerNull())
        //判断拖车还是自送
        if (mData.enterMode == "1") {
            tuoche.performClick()
            mTrackingLL.visibility = View.VISIBLE

        } else if (mData.enterMode == "2") {
            zisong.performClick()
        }

        mViewModel.result.observe(this, {
            loading.dismiss()
            MyLog.d("订单详情回调:$it")
            handlerHttpResult(it) {
                val data = getGson().fromJson(it, ServiceOrderDetailEntityV2::class.java).data
                data?.let {
                    mServiceRemarkET.textSet(data.remark.handlerNull())
                }
            }
        })
        mList.add(ServiceEditCheckBean("battery", "电瓶", true))
        mList.add(ServiceEditCheckBean("conveyorShaft", "传送轴", true))
        mList.add(ServiceEditCheckBean("waterTank", "水箱", true))
        mList.add(ServiceEditCheckBean("cab", "驾驶室", true))
        mList.add(ServiceEditCheckBean("highPressurePump", "高压泵", true))
        mList.add(ServiceEditCheckBean("bigBox", "大箱", true))
        mList.add(ServiceEditCheckBean("engine", "发动机", true))
        mList.add(ServiceEditCheckBean("crane", "起动机", true))
        mList.add(ServiceEditCheckBean("transmissionCase", "变速箱", true))
        mList.add(ServiceEditCheckBean("line", "线路", true))
        mList.add(ServiceEditCheckBean("condenser", "冷凝器", true))
        mList.add(ServiceEditCheckBean("carKey", "钥匙", true))
        mList.add(ServiceEditCheckBean("compressor", "压缩机", true))
        mList.add(ServiceEditCheckBean("steeringMachine", "方向机", true))
        mList.add(ServiceEditCheckBean("alternator", "发电机", true))
        mList.add(ServiceEditCheckBean("frontAxle", "前桥", true))
        mList.add(ServiceEditCheckBean("rearAxle", "后桥", true))
        mList.add(ServiceEditCheckBean("notice", "告知书", true))
        mList.add(ServiceEditCheckBean("attorneyPaper", "委托书", true))
        mList.add(ServiceEditCheckBean("plateApplicationForm", "机动车牌申领表", true))
        mList.add(ServiceEditCheckBean("drivingLicense", "行车证", true))
        mList.add(ServiceEditCheckBean("registration", "车辆登记证书", mData.drivingLicense == "1"))
        mList.add(ServiceEditCheckBean("idCardCopy", "身份证复印件", mData.registration == "1"))
        mList.add(ServiceEditCheckBean("doesGuaranteed", "保号", mData.idCardCopy == "1"))
        //处理选择
        mSelectRV.adapter = mAdapter
        mSelectRV.layoutManager = GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)

        mViewModel.payTypeResult.observe(this, {
            MyLog.d("收款方式:$it")
            handlerHttpResult(it) {
                val data = getGson().fromJson(it, PayTypeEntity::class.java)
                mPayTypeEntity = data
                data?.data?.let { bean ->
                    mAliPayBTN.isEnabled = false
                    mAliPayBTN.backgroundResource = R.drawable.bg_btn_gray_radius_5
                    mWeChatBTN.isEnabled = false
                    mWeChatBTN.backgroundResource = R.drawable.bg_btn_gray_radius_5
                    mBankBTN.isEnabled = false
                    mBankBTN.backgroundResource = R.drawable.bg_btn_gray_radius_5
                    mMoneyBTN.isEnabled = false
                    mMoneyBTN.backgroundResource = R.drawable.bg_btn_gray_radius_5
                    when (bean.paymentMethod) {
                        "1" -> {
                            //支付宝
                            mAliPayBTN.isEnabled = true
                            mAliPayBTN.backgroundResource = R.drawable.bg_solid_accent_radius5
                        }
                        "2" -> {
                            //微信
                            mWeChatBTN.isEnabled = true
                            mWeChatBTN.backgroundResource = R.drawable.bg_solid_accent_radius5
                        }
                        "3" -> {
                            //银行卡
                            mBankBTN.isEnabled = true
                            mBankBTN.backgroundResource = R.drawable.bg_solid_accent_radius5
                        }
                        "4" -> {
                            //现金
                            mMoneyBTN.isEnabled = true
                            mMoneyBTN.backgroundResource = R.drawable.bg_solid_accent_radius5
                        }
                    }
                }
            }
        })
    }

    override fun click() {
        //拖车
        tuocheTV.setOnClickListener { tuoche.performClick() }
        tuoche.setOnClickListener {
            if (tuoche.isChecked) {
                zisong.isChecked = false
            }
        }
        //自送
        zisongTV.setOnClickListener { zisong.performClick() }
        zisong.setOnClickListener {
            if (zisong.isChecked) {
                tuoche.isChecked = false
            }
        }


        tuoche.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                YoYo.with(Techniques.ZoomInRight).duration(300).playOn(mTrackingLL)
                mTrackingLL.visibility = View.VISIBLE
            } else {
                YoYo.with(Techniques.ZoomOut).duration(300).playOn(mTrackingLL)
                Handler().postDelayed({
                    mTrackingLL.visibility = View.GONE
                }, 300)
            }
        }


        //支付宝
        mAliPayBTN.setOnClickListener {
            payTypeDialog = ServicePayTypeDialog(mData.suborderId.handlerNull(), 1, mPayTypeEntity, this)
            payTypeDialog?.show(supportFragmentManager, "")
        }
        //微信
        mWeChatBTN.setOnClickListener {
            payTypeDialog = ServicePayTypeDialog(mData.suborderId.handlerNull(), 2, mPayTypeEntity, this)
            payTypeDialog?.show(supportFragmentManager, "")
        }
        //银行卡
        mBankBTN.setOnClickListener {
            payTypeDialog = ServicePayTypeDialog(mData.suborderId.handlerNull(), 3, mPayTypeEntity, this)
            payTypeDialog?.show(supportFragmentManager, "")
        }
        //现金
        mMoneyBTN.setOnClickListener {
            if (mPayTypeEntity?.data?.paymentMethod == "4") {
                mMoneyBTN.isEnabled = false
            } else {
                payTypeDialog = ServicePayTypeDialog(mData.suborderId.handlerNull(), 4, mPayTypeEntity, this)
                payTypeDialog?.show(supportFragmentManager, "")
            }
        }
        //提交订单
        mConfirmBTN.setOnClickListener {
            confirmHandler()
        }
        //取消订单
        mCancelBTN.setOnClickListener {
            val mServiceRemark = mServiceRemarkET.text.handlerNull()

            when {
                mServiceRemark.isEmpty() -> showToast("取消订单请输入客服备注")
                else -> {
                    mViewModel.serviceOrderCancel(mData.suborderId.handlerNull(), mData.carId.handlerNull(), mServiceRemark)
                }
            }
        }
        //订单属性 2:预订单 3:意向订单
        mTopBTN.setOnClickListener {
            when (dataType) {
                2 -> {
                    //订单待沟通
                    mViewModel.serviceOrderWaitTalk(mData.suborderId.handlerNull(), mData.carId.handlerNull())
                }
                3 -> {
                    //回访记录
                    startActivity<ServiceReturnRecordActivity>(MyConstants.SUBORDER_ID to mData.suborderId)
                }
            }
        }

        mViewModel.confirmResult.observe(this, {
            MyLog.d("提交回调:$it")
            handlerHttpResult(it) {
                showToast("提交订单成功")
                finish()
            }
        })

        mViewModel.cancelResult.observe(this, {
            MyLog.d("取消回调:$it")
            handlerHttpResult(it) {
                showToast("取消订单成功")
                finish()
            }
        })
        mViewModel.commonResult.observe(this, {
            MyLog.d("通用回调:$it")
            handlerHttpResult(it) {
                showToast("提交成功")
                finish()
            }
        })
    }

    //提交订单
    fun confirmHandler() {
        val mCarAddress = mCarAddressET.text.handlerNull()
        val mCarBrand = mCarBrandET.text.handlerNull()
        val mCarColor = mCarColorET.text.handlerNull()
        val mReceiver = mReceiverET.text.handlerNull()
        val mReceiverPhone = mReceiverPhoneET.text.handlerNull()
        val mSendAddress = mSendAddressET.text.handlerNull()
        val mServiceRemark = mServiceRemarkET.text.handlerNull()
        val enterMode = if (zisong.isChecked) "2" else "1"
        when {
            mCarAddress.isEmpty() -> showToast("请输入车辆所在位置")
            mCarBrand.isEmpty() -> showToast("请输入车辆品牌")
            mReceiver.isEmpty() -> showToast("请输入收件人姓名")
            mReceiverPhone.isEmpty() -> showToast("请输入收件人电话")
            //入场方式
            !zisong.isChecked && !tuoche.isChecked -> showToast("请选择车辆入场方式")
            tuoche.isChecked && trackingSelectPosition == 0 -> showToast("请选择物流公司")
            else -> {
                val map: MutableMap<String, Any> = HashMap()
                map["suborderId"] = mData.suborderId.handlerNull()
                map["carId"] = mData.carId.handlerNull()
                map["status"] = "2"
                map["carBrand"] = mCarBrand
                map["carColor"] = mCarColor
                map["carAddress"] = mCarAddress
                map["recipient"] = mReceiver
                map["recipientPhone"] = mReceiverPhone
                map["mailingAddress"] = mSendAddress
                map["enterMode"] = enterMode
                mList.forEach { bean ->
                    map[bean.idName] = if (bean.select) "1" else "0"
                }
                map["steelRingNum"] = gangquan.getCount()
                map["aluminumRingNum"] = lvquan.getCount()
                map["tyreNum"] = luntai.getCount()
                map["plateNum"] = chepai.getCount()
                map["remark"] = mServiceRemark
                if (tuoche.isChecked) {
                    map["lgsCompanyId"] = trackingList[trackingSelectPosition].id
                    map["lgsCompanyName"] = trackingList[trackingSelectPosition].orgname.handlerNull()
                }
                val obj = Gson().toJson(map)
                val body = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    obj
                )
                mViewModel.serviceOrderConfirm(body)
            }
        }
    }

    override fun onItemSelect(position: Int, select: Boolean) {
        mList[position].select = select
        mAdapter.notifyDataSetChanged()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        payTypeDialog?.onActivityResult(requestCode, resultCode, data)
    }


    //收款方式确定
    override fun confirm() {
        payTypeDialog?.dismiss()
        mViewModel.payType(mData.suborderId.handlerNull())
    }
}